define(function(require, exports)
{
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');
	var popwin	= require('@base/dialog').base;
	var grid    = require('@base/grid');
	var highGrid = require('@base/highGrid').base;

	var Main = view.container.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				class: 'M-promotionCondition',
				url: '',
				gridTitle: '',
				name: LANG('选择帐号'),
				view_model: {
					'List': [],
					'eventSelect': this.eventSelect,
					'eventDelete': this.eventDelete
				},
				grid_mod: '',
				param: null,
				show_hasSelect: true,
				singleSelect: false,
				popwin_config: {}
			});

			this.$data = {};
			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			var el = this.getDOM();
			var c = this.getConfig();
			var name = c.name;

			$([
				'<div class="M-promotionConditionSideBar">',
					'<span class="font-primary cur_p" ms-click="eventSelect">'+ name +'</span>',
					'<div ms-visible="List.length" class="selectContainer">',
						'<ul>',
							'<li ms-repeat-sel="List" class="dib">',
								'<span class="uk-text-truncate" ms-click="eventDelete($index)" title="'+ LANG('点击移除') +'">{{sel.Name}}<i class="icon-close cur_p"></i></span>',
							'</li>',
						'</ul>',
					'</div>',
				'</div>'
			].join('')).appendTo(el);

			this.create('select', SelectPopwin,
				util.extend({
					url: c.url,
					grid_mod: c.grid_mod,
					show_hasSelect: c.show_hasSelect,
					param: c.param,
					singleSelect: c.singleSelect,
					title: c.gridTitle
				}, c.popwin_config));

			this.buildFromTemplate({

			});
		},
		showSelect: function()
		{
			this.$.select.show().setData(this.$ids);
		},
		eventSelect: function()
		{
			this.showSelect();
		},
		eventDelete: function(index)
		{
			var list = this.vm.$.List;
			list.splice(index, 1);
			var ids = [];
			util.each(list, function(item) {
				ids.push(item._id);
			});

			this.$.select.setData(ids);

			var old = util.clone(this.$ids);
			this.$ids = ids;

			var name = [];
			var listData = this.$.select.getSelectedData();
			if (this.$ids.length) {
				for (var i = 0; i<this.$ids.length; i++) {
					var id = this.$ids[i];
					for (var j = 0; j<listData.length; j++) {
						var item = listData[j];
						if (id === item._id) {
							name.push(item.Name);
							break;
						}
					}
				}
			}
			else {
				name = [];
			}

			this.fire('selectChange', {
				'old': old,
				'new': this.$ids,
				'name': name
			});
		},
		onDialogOk: function()
		{
			var name = [];
			var listData = this.$.select.getSelectedData();
			listData.forEach(function(item){
				name.push(item.Name);
			});

			this.$.select.hide();
			this.fireSelectChange(name);
			this.load();
			this.fire('mainPopwinOk');

			return false;
		},
		onDialogCancel: function()
		{
			this.fire('selectCancel');
		},
		load: function()
		{
			var self = this;
			if (!this.$ids || !this.$ids.length)
			{
				this.$ids = [];
				this.vm.$.List = [];
				return false;
			}

			var param = this.getConfig('param');

			param = util.extend({}, param, {'ids': self.$ids, 'noLimit': true});

			pubjs.mc.send(
				self.getConfig('url'),
				param,
				function(err, data)
				{
					if (err)
					{
						pubjs.alert(err.message);
						return false;
					}
					self.$data = data;
					self.vm.$.List = data.items;
				}
			)
		},
		getValue: function()
		{
			return this.$ids || [];
		},
		setValue: function(ids)
		{
			this.$ids = ids || [];
			this.load();
			return this;
		},
		reset: function()
		{
			this.vm.reset();
			this.$ids = [];
			this.$.select.reset();
			// 发送事件selectChange，reset里面的name的值，供筛选栏删除显示的已选内容使用
			this.fireSelectChange([]);
			return this;
		},
		// 发送事件selectChange
		fireSelectChange: function(name){
			this.$ids = this.$.select.getData();
			var old = this.$ids;

			this.fire('selectChange', {
				'old': old,
				'name': name,
				'new': this.$ids
			});

			return this;
		}
	});

	exports.main = Main;


	var SelectPopwin = popwin.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				'silence': false,
				'url': '',
				'view_model': {
					'eventSelected': this.eventSelected
				},
				'grid_mod': '',
				'show_hasSelect': true,
				'singleSelect': false,
				'auto_load': true,
				'size': 'm'
			});


			this.$selected = false;

			// 内部变量，用于获取选择订单列表所有已选订单对应的data
			this.$gridChooseData = {
				'currentData': [],
				'chooseData': [],
				'modChooseData': function(data){
					var result = [];
					var param = data.param;

					// 所有页面已选订单的id
					var ids = param.selected;
					// 已经有的订单数据
					var existeData = this.chooseData;
					// 当前页面已选订单的data
					var currentData = this.currentData;
					// 合并已有的data和当前data，得到所有已选订单对应的data
					mixData = existeData.concat(currentData);

					for (var i = 0; i<ids.length; i++) {
						var id = ids[i];
						for (var j = 0; j<mixData.length; j++) {
							var item = mixData[j];
							if (+id === +item._id) {
								result.push(item);
								break;
							}
						}
					}

					this.chooseData = result;
				},
				'setCurrentData': function(data){
					this.currentData = data;
					return this;
				},
				'setChooseData': function(value){
					this.chooseData = value;
					return this;
				},
				'getChooseData': function(){
					return this.chooseData;
				}
			};

			this.Super('init', arguments);
		},
		afterBuild:function()
		{
			this.Super('afterBuild', arguments);
			var el = this.getDOM();
			var grid_mod = this.getConfig('grid_mod') || "modules/select.grid";
			$([
				'<span pub-name="grid" pub-mod="' + grid_mod + '"></span>',
				'<span class="selected">',
					'<input class="cur_p" type="checkbox" ms-click="eventSelected">',
					'<span class="ml5">'+ LANG('显示已选') + '</span>',
				'</span>'
			].join('')).appendTo(el);

			this.$selectEl = el.find('.selected').css(
				{
					'position': 'absolute',
					'top': '60px',
					'right': '40px'
				}
			);

			if (!this.getConfig('show_hasSelect'))
			{
				this.$selectEl.hide();
			}

			this.buildFromTemplate({
				'grid':{
					// 通知input选择事件
					eventSelect: true,
					url: this.getConfig('url'),
					param: this.getConfig('param'),
					singleSelect: this.getConfig('singleSelect'),
					auto_load: this.getConfig('auto_load')
				}
			});
		},
		setData: function(ids)
		{
			ids = util.clone(ids);
			this.$.grid.setSelectRowIds(ids || []);
			return this;
		},
		getData: function()
		{
			return util.clone(this.$.grid.getSelectRowIds() || []);
		},
		onChangeSelect: function(ev){
			var modName = ev.name;
			var cs = this.$;
			var ids = ev.param.selected;
			var currentData = cs.grid.getData(ids);

			this.$gridChooseData.setCurrentData(currentData);
			this.$gridChooseData.modChooseData(ev);
			return false;
		},
		getSelectedData: function(){
			return this.$gridChooseData.getChooseData();
		},
		setParam: function(param)
		{
			this.$.grid.setParam(param);
			return this;
		},
		show: function()
		{
			this.Super('show', arguments);
			// 已选去除勾选状态
			this.$selectEl.find('>input').attr('checked', false);
			this.$.grid.setParam({'ids': null});


			this.$.grid.reset().load();
			return this;
		},
		eventSelected: function()
		{
			this.$selected = !this.$selected;

			var ids = [];
			// 勾上已选
			if (this.$selected) {
				ids = this.getData();
				if (ids.length) {
					this.setParam({'ids': ids});
					this.$.grid.load();
				}
				else {
					this.$.grid.setData([]);
				}
			}
			else {
				this.setParam({'ids': null});
				this.$.grid.load();
			}
			return false;
		}
		,reset: function(){
			this.$.grid.setSelectRowIds([]);
			this.$.grid.load();
			return this;
		}
	});
	exports.popwin = SelectPopwin;


	var Grid = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				url: '',
				cols: [
					{name:'_id', text: LANG("ID"), sort: true, 'align': 'center'},
					{name:'UserName', text: LANG("名称"), width: 600, 'align': 'left'}
				],
				reqType: 'websocket',
				opClick: true,
				hasTab: false,
				hasMenu: false,
				hasPager: true,
				hasSearch: true,
				hasExport: false,
				hasAmount: false,
				auto_load: false,
				hasSelect: true,
				param: {
					limit: 8
				},
				pager: {
					size: 8,
					showSizeTypes: 0,
					showJumper: 0
				}
			});

			this.Super('init', arguments);
		}
	});

	exports.grid = Grid;
	var NameGrid = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				url: '',
				cols: [
					{name:'_id', text: LANG("ID"), sort: true, 'align': 'center'},
					{name:'Name', text: LANG("名称"), width: 600, 'align': 'left'}
				],
				reqType: 'websocket',
				opClick: true,
				hasTab: false,
				hasMenu: false,
				hasPager: true,
				hasSearch: true,
				hasExport: false,
				hasAmount: false,
				auto_load: false,
				hasSelect: true,
				param: {
					limit: 8
				},
				pager: {
					size: 8,
					showSizeTypes: 0,
					showJumper: 0
				}
			});
			this.Super('init', arguments);
		}
	});
	
	exports.nameGrid = NameGrid;
	var SourceType = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				url: '',
				cols: [
					//{name:'_id', text: LANG("ID"), sort: true, 'align': 'center'},
					{name:'Name', text: LANG("名称"), width: 600, 'align': 'left'}
				],
				reqType: 'websocket',
				opClick: true,
				hasTab: false,
				hasMenu: false,
				hasPager: true,
				hasSearch: false,
				hasExport: false,
				hasAmount: false,
				auto_load: false,
				hasSelect: true,
				param: {
					limit: 8
				},
				pager: {
					size: 8,
					showSizeTypes: 0,
					showJumper: 0
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			this.Super('afterBuild', arguments);
			var el = this.getDOM();
			el.addClass('mt20');
		}
	});

	exports.sourceType = SourceType;

	var DealGrid = highGrid.extend({
		init: function(config){
			config = pubjs.conf(config, {
				cols: [
					{name: "_id", text:LANG("ID"), width:50, align: 'center'},
					{name: 'Name', text:LANG("订单名称"), width:200, align:'left',render:'renderName'},
					{name: 'Time', text: LANG('订单时间'), width:100},
					{name: 'Price', text: LANG('订单价格'), width:100},
					{name: 'Status', text:LANG('状态'),  align:'center', width: 50}
				],
				metrics: [
					{name: 'channelName', text:LANG('渠道'), align:'center'},
					{name: 'SpotsInfo', text:LANG('广告位数量'), align:'center'},
					{name: 'UpdateTime', text:LANG('更新时间'), align:'center'}
				]
				,'hasExport': false
				,'hasRefresh': false
				,'hasAmount': false
				,'hasSubGrid': false
				,'hasTab': false
				,'hasFixedHeightBtn': false
				,'hasSelect': true
				,'hasFilter': false
				,'reqType': 'websocket'
				,'pager': {'size':10}
				,'hasFilterResult':false
				,'hasFilter':false
			});

			this.Super('init', arguments);
		},
		renderName: function(i, val, row, con){
			return $('<div class="text-truncate"/>').width(200).text(val).attr('title', val);
		}
	});

	exports.dealGrid = DealGrid;
	
	var QualificationGrid = Grid.extend({
		init: function(config){
			config = pubjs.conf(config, {
				url: '',
				cols: [
					{name:'_id', text: LANG("ID"), sort: true, 'align': 'center'},
					{name:'UserName', text: LANG("名称"), width: 600, 'align': 'left'}
				],
				param: {
					limit: 8
				},
				pager: {
					size: 1,
					showSizeTypes: 0,
					showJumper: 0
				}
			});

			this.Super('init', arguments);
		}
	});
	exports.qualificationGrid = QualificationGrid;

});